package org.jim.server.command.handler;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.config.ImConfig;
import org.jim.core.exception.ImException;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.ChatType;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.server.ImServerChannelContext;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.config.ImServerConfig;
import org.jim.server.protocol.ProtocolManager;
import org.jim.server.queue.MsgQueueRunnable;
import org.jim.server.util.ChatKit;
import java.util.Objects;

/**
 * 版本: [1.0]
 * 功能说明: 聊天请求cmd消息命令处理器
 * @author : WChao 创建时间: 2017年9月22日 下午2:58:59
 */
public class ChatReqHandler extends AbstractCmdHandler {

	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException {
		if (packet.getBody() == null) {
			throw new ImException("body is null");
		}
		ChatBody chatBody = ChatKit.toChatBody(packet.getBody(), channelContext);
		packet.setBody(chatBody.toByte());
		//聊天数据格式不正确
		if(chatBody == null || ChatType.forNumber(chatBody.getChatType()) == null){
			ImPacket respChatPacket = dataInCorrect(channelContext);
			return respChatPacket;
		}
		//聊天前业务处理（比如格式判断、好友判断等）
		ImPacket beforeImPacket = beforeChat(chatBody, channelContext);
		if(beforeImPacket != null) return beforeImPacket;
		// 转接用户(比如客服场景)
		chatBody.setTo(switchTo(channelContext.getUserId(), chatBody.getTo()));
		//异步调用业务处理消息接口
		addQueueMsgProcessor(getSingleProcessor(),channelContext, chatBody);
		ImPacket chatPacket = new ImPacket(Command.COMMAND_CHAT_REQ,new RespBody(Command.COMMAND_CHAT_REQ,chatBody).toByte());
		//设置同步序列号;
		chatPacket.setSynSeq(packet.getSynSeq());
		ImServerConfig imServerConfig = ImConfig.Global.get();
		boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
		//私聊
		if(ChatType.CHAT_TYPE_PRIVATE.getNumber() == chatBody.getChatType()){
			String toId = chatBody.getTo();
			if(ChatKit.isOnline(toId, isStore)){
				sendToUser(toId, chatPacket);
				//发送成功响应包
				return success(channelContext);
			}else{
				//用户不在线响应包
				return offline(channelContext);
			}
		//群聊
		}else if(ChatType.CHAT_TYPE_PUBLIC.getNumber() == chatBody.getChatType()){
			String groupId = chatBody.getGroupId();
			sendToGroup(groupId, chatPacket);
			//发送成功响应包
			return success(channelContext);
		}
		return null;
	}
	/**
	 * 聊天前业务处理（比如格式判断、好友判断等）
	 * @param body
	 * @param channelContext
	 * @return
	 * @throws ImException
	 */
	public ImPacket beforeChat(ChatBody body, ImChannelContext channelContext) throws ImException {
		return null;
	}

	/**
	 * 转接聊天对象
	 * @param userId
	 * @param toUserId
	 * @return
	 */
	public String switchTo(String userId, String toUserId){
		return toUserId;
	}
	/**
	 * 发送给目标用户，独立出来方便拓展格式
	 * @param toId
	 * @param packet
	 */
	public void sendToUser(String toId, ImPacket packet){
		JimServerAPI.sendToUser(toId, packet);
	}
	/**
	 * 发送给目标群组
	 * @param groupId
	 * @param packet
	 */
	public void sendToGroup(String groupId, ImPacket packet){
		JimServerAPI.sendToGroup(groupId, packet);
	}
	/**
	 * 发送成功响应包
	 * @param channelContext
	 * @return
	 * @throws ImException
	 */
	public ImPacket success(ImChannelContext channelContext) throws ImException{
		return ProtocolManager.Packet.success(channelContext);
	}
	/**
	 * 用户不在线响应包
	 * @param channelContext
	 * @return
	 * @throws ImException
	 */
	public ImPacket offline(ImChannelContext channelContext) throws ImException{
		return ProtocolManager.Packet.offline(channelContext);
	}

	/**
	 * 数据格式不正确响应包
	 * @param channelContext
	 * @return
	 * @throws ImException
	 */
	public ImPacket dataInCorrect(ImChannelContext channelContext) throws ImException {
		return ProtocolManager.Packet.dataInCorrect(channelContext);
	}

	@Override
	public Command command() {
		return Command.COMMAND_CHAT_REQ;
	}
}
